<?php

class ImportDbForm extends CFormModel
{
	const LIMIT = 1000;

	public $driver;
	public $hostname = 'localhost';
	public $dbuser = 'root';
	public $dbpass;
	public $dbname;
	public $queryString = 'SELECT * FROM tbl_post';
	public $offset = -1;

	/**
	 * @var XSDataSource 
	 */
	private $_ds;

	public function rules()
	{
		return array(
			array('driver, dbname, queryString', 'required'),
			array('offset', 'numerical'),
			array('hostname, dbuser, dbpass', 'safe'),
			array('driver', 'connect'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'driver' => '数据库类型',
			'hostname' => '主机地址',
			'dbuser' => '用户名',
			'dbpass' => '密码',
			'dbname' => '数据库名/路径',
			'queryString' => 'SQL 查询语句',
		);
	}

	public function connect($attribute, $params)
	{
		if ($this->hasErrors()) {
			return;
		}
		if (stristr($this->queryString, ' LIMIT ')) {
			return $this->addError('queryString', 'SQL 语句中不能包含 LIMIT 和 OFFSET');
		}
		if (strncasecmp($this->queryString, 'SELECT ', 7)) {
			return $this->addError('queryString', 'SQL 语句必须以 SELECT 开头');
		}
		$source = '';
		switch ($this->driver) {
			case 'mysql':
			case 'pgsql':
				if (!$this->hostname) {
					$this->addError('hostname', '数据库连接地址不能为空');
				} elseif (!$this->dbuser) {
					$this->addError('dbuser', '用户名不能为空');
				}
				$source = $this->driver . '://' . $this->dbuser . ':' . $this->dbpass . '@' . $this->hostname . '/' . $this->dbname;
				break;
			case 'sqlite':
				$source = 'sqlite://' . $this->dbname;
				break;
			case 'sqlite3':
				$source = 'sqlite3://' . $this->dbname;
				break;
			default:
				$this->addError('driver', '不支持数据源：' . $this->driver);
				break;
		}
		if (!$this->hasErrors()) {
			require_once Yii::app()->pf->sdkRoot . '/php/util/XSDataSource.class.php';
			try {
				$query = $this->queryString . ' LIMIT ' . self::LIMIT . ' OFFSET ' . max(0, $this->offset);
				$this->_ds = XSDataSource::instance($source, $query);
			} catch (XSException $e) {
				$this->addError($attribute, $e->getMessage());
			}
		}
	}

	public function getData()
	{
		return $this->_ds->getData();
	}

	public function dbDrivers()
	{
		return array(
			'mysql' => 'MySQL',
			'pgsql' => 'PostgresSQL',
			'sqlite3' => 'SQLite 3.x',
			'sqlite' => 'SQLite 2.x',
		);
	}
}
